/**
 * @author: jinxl521@qq.com
 * @module:公共方法
 * @explain:状态管理
 */

const storage = {
  /* Cookie操作 */
  setCookie: function (key, value, iDay = 1) {
    const oDate = new Date()
    oDate.setDate(oDate.getDate() + iDay)
    document.cookie = key + '=' + value + ';expires=' + oDate
  },
  getCookie: function (key) {
    const cookieArr = document.cookie.split('; ')
    for (let i = 0; i < cookieArr.length; i++) {
      const arr = cookieArr[i].split('=')
      if (arr[0] === key) {
        return arr[1]
      }
    }
    return false
  },
  removeCookie (key) {
    storage.setCookie(key, '', -1)
  },
  /* localStorage
   * 没有时间限制的数据存储
   * */
  setLocalStorage: function (key, value) {
    localStorage.setItem(key, value)
  },
  getLocalStorage: function (key) {
    return localStorage.getItem(key)
  },
  removeLocalStorage: function (key) {
    localStorage.removeItem(key)
  },
  emptyLocalStorage: function () {
    localStorage.clear()
  },
  /* 将JSON存储到localStorage里 */
  jsonSaveLocalStorage: function (jsonName, jsonObj) {
    const _jsonObj = JSON.stringify(jsonObj)// JavaScript （通常为对象或数组）值转换为 JSON 字符串
    localStorage.setItem(jsonName, _jsonObj)
    // let jsonObj = JSON.parse(localStorage.getItem(jsonName));//取值，然后转换为JSON对象；
  }

  /* sessionStorage
   * 会话结束/关闭窗口，存储的数据清空
   * */
}
export default storage
